import Immutable from 'immutable';

import { jssdkConfig } from '../services/wechat';
import { scan, getLocation, setTitle } from '../utils/wechat';
import { DEBUG } from '../constants/setting';

function getCommonTitle(pathname) {
  let title = '鱿鱼加油';
  if (pathname.indexOf('/tmall') !== -1) {
    title = '天猫加油';
  } else if (pathname.indexOf('/station') !== -1) {
    title = '附近油站';
  } else if (pathname.indexOf('/pay/') !== -1) {
    title = '收银台';
  } else if (pathname.indexOf('/escort') !== -1 || window.source === 'GDBJYY') {
    title = '保驾车服';
  } else if (pathname.indexOf('/qiji/') !== -1) {
    title = '汽集网';
  }
  return title;
}

function checkTitle(pathname) {
  switch (pathname) {
    case '/tmall/couponList':
      setTitle('天猫加油');
      break;
    case '/cq/refuel':
      setTitle('订单确认');
      break;
    case '/pay/pay':
      setTitle('确认订单');
      break;
    case '/cq/result':
      setTitle(window.source === 'TAOBAO' ? '天猫加油' : '鱿鱼加油');
      break;
    case '/cq/userCenter':
      setTitle('我的');
      break;
    case '/cq/giftCenter':
      setTitle('优惠中心');
      break;
    case '/cq/home':
      setTitle(window.source === 'TAOBAO' ? '天猫加油' : '鱿鱼加油');
      break;
    case '/app/loginWithCode':
      setTitle('登录中');
      break;
    case '/app/500':
      setTitle('出错啦');
      break;
    default:
      setTitle(getCommonTitle(pathname));
      break;
  }
}

const BannerRecord = Immutable.Record({
  picPath: null,
  urlPath: null,
}, 'Banner');

export class Banner extends BannerRecord {
}

const MenuRecord = Immutable.Record({
  title: null,
  icon: null,
  code: null,
});

export class Menu extends MenuRecord {
  action(history, dispatch, proj) {
    console.log(proj);
    switch (this.get('code')) {
      default:
        break;
    }
  }
}


export default {
  namespace: 'global',

  state: Immutable.fromJS({
    scanResult: null,
    geoData: {},
    jssdkReady: false,
    resource: {
      giftCenter: {
        menuList: [],
        bannerList: [],
      },
      userCenter: {
        menuList: [],
      },
    },
  }),

  effects: {
    initJssdk: [function* (_, { call, put }) {
      const url = window.location.href.split('#')[0];
      const res = yield call(jssdkConfig, url);
      if (res.success && window.wx) {
        const signData = {
          signature: res.data.signature,
          timestamp: res.data.timestamp,
          nonceStr: res.data.nonStr,
          url,
          appId: res.data.appId,
        };

        window.wx.config({
          ...signData,
          jsApiList: ['openLocation', 'scanQRCode', 'getLocation'],
          debug: false,
        });
        yield put({
          type: 'updateJssdkReady',
          payload: true,
        });
      }
    }, { type: 'throttle', ms: 1000 }],
    *wxGeo(_, { call, put, select }) {
      const ready = yield select(state => state.global.get('jssdkReady'));
      if (!ready) {
        yield put.resolve({
          type: 'initJssdk',
        });
      }
      try {
        const data = yield call(getLocation);
        yield put({
          type: 'updateGeoData',
          payload: data,
        });
      } catch (error) {
        if (DEBUG) {
          // eslint-disable-next-line
          alert(`微信定位失败:${JSON.stringify(error)}`);
        }
        console.error(error);
      }
    },
    *wxScan(_, { call, put, take }) {
      yield put({
        type: 'updateScanResult',
        payload: null,
      });
      yield put({
        type: 'initJssdk',
      });
      yield take('global/initJssdk/@@end');
      console.log('完成扫码前jssdk初始化');
      try {
        const data = yield call(scan);
        yield put({
          type: 'updateScanResult',
          payload: data,
        });
      } catch (error) {
        console.error(error);
      }
    },
  },

  reducers: {
    updateJssdkReady(state, { payload }) {
      return state.set('jssdkReady', payload);
    },
    updateGeoData(state, { payload }) {
      return state.set('geoData', Immutable.fromJS(payload));
    },
    updateScanResult(state, { payload }) {
      return state.set('scanResult', payload);
    },
    updateConfigData(state, { payload }) {
      return state.setIn(['configData', payload.url], payload.data);
    },
  },
  subscriptions: {
    stepup({ history, dispatch }) {
      if (window.wx) {
        window.wx.error((res) => {
          console.error('微信error', res);
          dispatch({
            type: 'global/updateJssdkReady',
            payload: false,
          });
        });
      }
      return history.listen(({ pathname }) => {
        console.log('------->', pathname);
        checkTitle(pathname);
        if (window.MtaH5) {
          window.MtaH5.pgv();
        }
      });
    },
  },
};
